import store from '@/store'
import tinymce from 'tinymce/tinymce'

function checkContainer(el) {
  if (el?.nodeType === 3) {
    if (el.length === 0) {
      return checkContainer(el.parentNode)
    }
    return false
  } else {
    return tinymce.DOM.is(el, '.irremovable')
  }
}

function getRemovableParagraph(el) {
  let p = null
  if (el?.nodeType === 3) {
    const str = el.textContent.replace(/\u200B/g, '')
    if (str === "") {
      p = el.parentElement
    }
  } else if (tinymce.DOM.is(el, 'p')) {
    p = el.textContent.length ? null : el
  }
  return p
}

/** 阻止 Backspace Delete 按键将页脚等元素删除 */
tinymce.PluginManager.add('irremovable', function (editor) {
  editor.on('keydown', function (event) {
    const { collapsed, startContainer, endContainer } = editor.selection.getRng() || {}
    const prevent = (event) => {
      console.log('===event prevented===')
      event.preventDefault()
      event.stopPropagation()
    }

    if (collapsed) {
      if (event.key === 'Backspace') {
        if (tinymce.DOM.is(startContainer?.previousElementSibling, 'div[data-type="terms"]')) {
          store.commit('xmleditor/SET_REMOVE_TERM_BLOCK_ID', startContainer?.previousElementSibling?.dataset?.blockId)
          return setTimeout(() => store.commit('xmleditor/REMOVE_TERM_BLOCK'))
        }

        if (getRemovableParagraph(startContainer)) {
          return
        }

        if (checkContainer(startContainer?.previousElementSibling) || checkContainer(startContainer)) {
          prevent(event)
        }
      }
      if (event.key === 'Delete') {
        if (tinymce.DOM.is(endContainer?.nextElementSibling, 'div[data-type="terms"]')) {
          store.commit('xmleditor/SET_REMOVE_TERM_BLOCK_ID', endContainer?.nextElementSibling?.dataset?.blockId)
          return setTimeout(() => store.commit('xmleditor/REMOVE_TERM_BLOCK'))
        }

        if (getRemovableParagraph(startContainer)) {
          return
        }

        if (checkContainer(endContainer?.nextElementSibling) || checkContainer(endContainer)) {
          prevent(event)
        }
      }
    } else {
      const bodys = ['body', '.page-body', '.page_body']
      if (event.key === 'Backspace') {
        if (bodys.some(item => tinymce.DOM.is(startContainer, item))) {
          prevent(event)
        }
      }

      if (event.key === 'Delete') {
        if (bodys.some(item => tinymce.DOM.is(endContainer, item))) {
          prevent(event)
        }
      }
    }
  })

  return {
    getMetadata: function () {
      return {
        name: '不可移除',
        url: 'http://sfrj.cn'
      }
    }
  }
})
